package cc.telecomdigital.tdstock.activity.groups.more;

import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.ProgressDialog;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.CommonDefn.ModeType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.INetworkChangeListener;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.HttpHelper;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.Data;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.NotificationSwitch;

/**
 * 
 * Project：tdstock3
 * Package：cc.telecomdigital.tdstock.activity.groups.more.push.setting
 * Class：MessageSettingActivity Description： Creater：hunter
 * [chengpanggang@126.com//hunter@mango.cc] CreateTime：Date：Oct 31, 2011
 * Time：10:28:36 AM Modifier ：hunter [chengpanggang@126.com//hunter@mango.cc]
 * Modify time： Date：Oct 31, 2011 Time：10:28:36 AM Modify Remarks：
 * 
 * @version
 * 
 */
public class MessageSettingActivity extends/* Activity_Framework*/  BaseActivity implements
		OnClickListener,  INetworkChangeListener{

	private Button breturn;
	private WebView webview;
	public static  final String TAG=MessageSettingActivity.class.getSimpleName();
	private static String url = "http://%s/notification/subscription.do?account=%s&token=%s&device_token=%s&device_type=2&view=gphone&version=1.0";
//	private String array[] = new String[] { "00:00", "01:00", "02:00", "03:00",
//			"04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00",
//			"11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00",
//			"18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00" };
	public static boolean flag = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if(((ITDLApplication)this.getApplicationContext()).getModeType()==ModeType.DELARY){
			setContentView(R.layout.more_message_delay);
			Button _toolBtnReturn = (Button) findViewById(R.id.more_message_returnbtn);
			_toolBtnReturn.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					TDStockLog.d(TAG, "close current activity and forwarding to the previous");

					Intent intent = new Intent(getApplicationContext(), MoreActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
					SwitchForwardActivity(MoreActivity.class, intent);
				}
			});
		}else{
					this.setContentView(R.layout.stock_message_setting);
					//windowWith=getWindow().getWindowManager().getDefaultDisplay().getWidth();
					breturn=(Button)findViewById(R.id.more_message_setting_return);
				
					//hanlder=new Handler();
			//		rg=(RadioGroup)findViewById(R.id.radioGroup1);
			//		rg.
					breturn.setOnClickListener(this);
					
					
			          ViewGroup container = (ViewGroup)findViewById(R.id.message_setting_container);
					
					
			          
			          //add the webview by program for avoiding android.view.WindowManager$BadTokenException: Unable to add window
			          //-- token android.app.LocalActivityManager$LocalActivityRecord@44ed8338 is not valid; is your activity running?
					 webview = new WebView(this.getParent() == null ? this : this.getParent());
					 
					webview.getSettings().setJavaScriptEnabled(true);
					
					webview.setScrollbarFadingEnabled(true);
					webview.setScrollContainer(true);
					webview.setVerticalScrollBarEnabled(false);
					webview.setHorizontalScrollBarEnabled(false);
//					webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//					webview.getSettings().setUseWideViewPort(true);
					
					webview.setWebViewClient(new WebViewClient(){
			
						@Override
						public boolean shouldOverrideUrlLoading(WebView view, String url) {
							// TODO Auto-generated method stub
							webview.loadUrl(url);
							return true;
						}
			
			
						
					});
					
					webview.requestFocus();
					
					/*webview.setOnTouchListener(new OnTouchListener() {
						@Override
						public boolean onTouch(final View v, MotionEvent event) {
							switch (event.getAction()) {
			            		case MotionEvent.ACTION_UP:
			            		case MotionEvent.ACTION_DOWN:
			            			 if (!v.hasFocus())
			                         {
			                             v.requestFocus();
			                         }
			            			 break;
			            			
							}
							
							return false;
						}
						
						
					});*/
			
					 //RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT,  RelativeLayout.LayoutParams.WRAP_CONTENT);
					RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT,  RelativeLayout.LayoutParams.FILL_PARENT);
					 param.addRule(RelativeLayout.BELOW ,R.id._stock_message_setting_ctn_top);
					
					container.addView(webview, param);
		}
	    //add the webview by program for avoiding android.view.WindowManager$BadTokenException: Unable to add window
        //-- token android.app.LocalActivityManager$LocalActivityRecord@44ed8338 is not valid; is your activity running?
	}
		


	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
//		Intent intent = new Intent(getApplicationContext(), MoreActivity.class);
//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//				| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//		SwitchForwardActivity(MoreActivity.class, intent);
		
		//SwitchBackActivity();  //this is not stable
		
		TDStockLog.d(TAG, "close current activity and forwarding to the previous");

		TDStockLog.d(TAG, "close current activity and forwarding to the previous");

		Intent intent = new Intent(getApplicationContext(), MoreActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		SwitchForwardActivity(MoreActivity.class, intent);
		
	}

	public String getSettingURL() {
		// String
		// s=String.format(MessageSettingActivity.url,"quotedev3.telecomdigital.cc",((ITDLApplication)getApplicationContext()).getSessionAccount(),((ITDLApplication)getApplicationContext()).getSessionToken(),MessageSettingActivity.device_token);
		Data.getDomainAndAccountAndTokenAndDevice_token(this);
		String s = String
				.format(MessageSettingActivity.url,
						Data.webServer,
						Data.account,
						Data.token,
						Data.device_token);
		TDStockLog.d(TAG, "url-------->" + s);
		return s;
	}

	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(((ITDLApplication)this.getApplicationContext()).getModeType()==ModeType.DELARY)
		{
			
		}else{
		    NotificationSwitch.getInstace().onSwitch(this);
		}
		
	}



	public void onResume(){
		super.onResume();
		if(((ITDLApplication)this.getApplicationContext()).getModeType()==ModeType.DELARY)
		{
			
		}else{
		            new Setting(this.getParent() == null ? this : this.getParent() ).execute();
		}
	}
  class Setting extends AsyncTask<Void, Void, Void>{
	  private ProgressDialog pd;
	  private Context context;
	  String  settingURL;
	  public Setting(Context context){
		  this.context=context;
	  }
	/* (non-Javadoc)
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Void doInBackground(Void... params) {
		settingURL= HttpHelper.isServerAvaiable(getSettingURL(), context, 1);
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		
		if(null!=settingURL&&!"".equals(settingURL)) {
			webview.post( new Runnable(){
					public void run(){
						webview.loadUrl(getSettingURL());
					}
			});
			
		}
		else {
			
			webview.post( new Runnable(){
				public void run(){
					String  content = MessageSettingActivity.this.getResources().getString(R.string.service_not_available);
					String summary = "<html><body><div>"
						+ content.replaceAll("[\n]", "<br>").replaceAll(
								"&gt;", ">").replaceAll("&lt;", "<")
								.replaceAll("&amp;", "&")
						+ "</div></body></html>";
					webview.loadDataWithBaseURL(null, summary, "text/html","utf-8", null);
				}
		});
			
			
		}
		
		ProgressDialog.dismissAll();
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		pd=new ProgressDialog(context,context.getString(R.string.downing));
		pd.show();
	}
	
 }
  
  
  @Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}
  
  
	@Override
	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo) {

		//super.NetworkChange_Response(iConnect, iNetInfo);
		if(iNetInfo.isAvailable() || iNetInfo.isConnected()) {
			if(((ITDLApplication)this.getApplicationContext()).getModeType()==ModeType.DELARY){
				
			}else{
			       new Setting(this.getParent() == null ? this : this.getParent() ).execute();
			}
		}
		
	}
	
	
	
  
  
}
